//防止csrf攻击
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

//弹框
function openWindow(content,title,width,height) {
    if(!title){
        title = '窗口';
    }
    var isFull = false;
    if(!width){
        width = $(window).width()+'px';
        isFull = true;
    }
    if(!height){
        //height = $(window).height()+'px';
        height = "100%";
    }
    var index = layui.layer.open({
        title:title,
        type:2,
        area:[width,height],
        maxmin:true,
        content:content,
        success:function (layro,index) {
            setTimeout(function(){
                layui.layer.tips('点击此处返回', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
            },500)
        }
    });
    //全屏弹框自适应
    $(window).on('resize',function () {
        if(isFull){
            layui.layer.full(index);
        }
    })
}
//提交确认，通过post方法
function goConfirm(url,data,msg,type) {
    if(!url){
        layer.msg('链接缺失');
        return false;
    }
    if(!msg){
        msg = '确定该操作';
    }
    if(!data){
        data = { };
    }
    if(!type){
        type = 0;
    }
    layer.confirm(msg,{btn:['确定','取消']},function () {
        var loadIndex = layer.load();
        $.post(url,data,function(res){
            layer.close(loadIndex);
            if(res.status == 200){
                layer.msg(res.msg,{icon:6,time:1500},function () {
                    if(type == 0){
                        //刷新本页
                        window.location.reload();
                    }else if(type == 1){
                        //关闭iframe，刷新父页
                        layer.closeAll("iframe");
                        //刷新父页面
                        parent.location.reload();
                    }else if(type == 2){
                        //关闭iframe
                        layer.closeAll("iframe");
                    }else if(type == 3){
                        //无操作
                    }
                })
            }else {
                layer.msg(res.msg,{icon:5,time:1500})
            }
        },'json');
    })
}
//提交确认，通过get方法
function goGetConfirm(url,data,msg,type) {
    if(!url){
        layer.msg('链接缺失');
        return false;
    }
    if(!msg){
        msg = '确定该操作';
    }
    if(!data){
        data = { };
    }
    if(!type){
        type = 0;
    }
    layer.confirm(msg,{btn:['确定','取消']},function () {
        var loadIndex = layer.load();
        $.get(url,data,function(res){
            if(res.status == 200){
                layer.close(loadIndex);
                layer.msg(res.msg,{icon:6,time:1500},function () {
                    if(type == 0){
                        //刷新本页
                        window.location.reload();
                    }else if(type == 1){
                        //关闭iframe，刷新父页
                        layer.closeAll("iframe");
                        //刷新父页面
                        parent.location.reload();
                    }else if(type == 2){
                        //关闭iframe
                        layer.closeAll("iframe");
                    }else if(type == 3){
                        //无操作
                    }
                })
            }else {
                layer.msg(res.msg,{icon:5,time:1500})
            }
        },'json');
    })
}
//post提交数据
function goPost(url,data) {
    if(!data){
        data = {}
    }
    $.post(url,data,function (res) {
        if(res.status == 200){
            layer.msg(res.msg,{icon:6,time:1500})
        }else {
            layer.msg(res.msg,{icon:5,time:1500})
        }
    },'json')
}
//get请求
function goGet(url,data) {
    if(!data){
        data = {}
    }
    $.get(url,data,function (res) {
        if(res.status == 200){
            layer.msg(res.msg,{icon:6,time:1500})
        }else {
            layer.msg(res.msg,{icon:5,time:1500})
        }
    },'json')
}
//获取地址栏的参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r!=null) return unescape(r[2]); return null; //返回参数值
}
//构建select下拉option
function buildOptions(url,data,elem,idName,valueName,selectedId,needClear=true) {
    $.get(url,data,function (res) {
        if(res.status == 200){
            if(needClear){
                $(elem).empty();
            }
            var html = '';
            $.each(res.data,function (index,item) {
                if(selectedId == item[idName]){
                    html += "<option value='"+item[idName]+"' selected>"+item[valueName]+"</option>";
                }else {
                    html += "<option value='"+item[idName]+"'>"+item[valueName]+"</option>";
                }
            });
            $(elem).append(html);
            layui.form.render();
        }
    },'json')
}
//图片上传--开始
$('body').on('click','.image-upload-btn',function () {
    $(this).next('input.upload-image').click();
    return false;
});
$('body').on('change','input.upload-image',function (event) {
    event.preventDefault();
    var image = this.files[0];
    var previewBox = $(this).next(".image-preview-box");
    var field = $(this).attr('data-field');
    var isMulti = $(this).attr('data-multi');
    previewImage(image,previewBox,field,isMulti)
});
//图片预览
function previewImage(image,previewBox,field,isMulti=0) {
    var randomNum = Math.ceil(Math.random()*100)+'';
    var reader = new FileReader();
    reader.readAsDataURL(image);
    reader.onload=function (e) {
        if(!isMulti || isMulti == '0'){
            previewBox.empty();
        }
        var html = '';
        html += "<div class='layui-col-md3' id='box"+randomNum+"' style='width: 300px;height: 220px;overflow:hidden;margin-right:10px;margin-top:10px;position:relative'>";
        html += "<img src='"+this.result+"' style='width: 300px;height: auto'/>";
        html += "<span class='layui-btn layui-btn-sm layui-btn-warm' style='position:absolute;left:10px;bottom:-5px' id='del"+randomNum+"' onclick='delImage(this)'>删除</span>";
        html += "<span class='layui-btn layui-btn-sm' style='position:absolute;left:50px;bottom:-5px' id='upload"+randomNum+"' onclick='uploadImage(this)'>上传</span>";
        html += "<input type='hidden' name='"+field+"' value=''/>";
        html += "</div>";
        previewBox.append(html);
    };
}
//删除图片
function delImage(obj) {
    $(obj).parent().remove();
}
//上传图片操作
function uploadImage(obj) {
    var myFile = $(obj).parent().parent('div.image-preview-box').prev('input.upload-image');
    var file = myFile[0].files[0];
    var tag = myFile.attr('data-tag');
    var url = myFile.attr('data-url');
    if(!url){
        console.log('上传地址参数未配置');
        return false;
    }
    console.log(file);
    if(tag == 'undefined' || tag == ''){
        tag = 'posts'
    }
    var formData=new FormData();
    //formData.append("image",file);
    formData.append("image",file);
    formData.append('tag',tag);
    console.log(formData);
    $.ajax({
        url: url,
        type: 'POST',
        processData: false,
        contentType: false,
        data: formData,
        dataType: "json",
        success: function (res) {
            if(typeof(res) == 'string'){
                res = $.parseJSON(res);
            }
            //console.log(res);
            if (res.status == 200) {
                $(obj).hide();
                $(obj).next("input[type='hidden']").val(res.data.url);
                layer.msg(res.msg,{time:1500,icon:6});
            } else {
                layer.msg(res.msg,{time:1500,icon:5});
            }
        },
        error: function (res) {
            console.log(res);
        }
    });
    return false;
}
//创建图片存放框
function createImageBox(id,field,url) {
    var html = '';
    if(url){
        html += "<div class='layui-col-md3' id='box"+id+"' style='width: 300px;height: 220px;overflow:hidden;margin-right:10px;margin-top:10px;position:relative'>";
        html += "<img src='"+url+"' style='width: 300px;height: auto'/>";
        html += "<span class='layui-btn layui-btn-sm layui-btn-warm' style='position:absolute;left:10px;bottom:-5px' id='del"+id+"' onclick='delImage(this)'>删除</span>";
        html += "<input type='hidden' name='"+field+"' value='"+url+"'/>";
        html += "</div>";
    }
    return html;
}
//图片上传--结束
//删除数组中某个元素
function removeArrayItem(arr,item) {
    var index = arr.indexOf(item);
    if(index > -1){
        arr.splice(index,1);
    }
    return arr;
}
//数组去重
function arrayUnique(arr) {
    var newArr = [];
    if(arr.length > 0){
        for (var i=0;i<arr.length;i++){
            if(newArr.indexOf(arr[i]) == -1){
                newArr.push(arr[i]);
            }
        }
    }
    return newArr;
}